package com.example.controller;


import com.example.common.result.Result;
import com.example.mapper.KucunMapper;
import com.example.service.INVMLService;
import com.example.service.KucunService;
import com.example.entity.dto.KucunyuliangDto;
import com.example.entity.dto.ShaomiaoDTO;
import com.example.entity.mes.INVML;
import com.example.entity.vo.KucunyuliangVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/Kuchun")
@Api(tags = "库存余量")
@Slf4j
public class kucunController {
    @Autowired
    private KucunService kucunService;

    @Autowired
    private KucunMapper kucunMapper;

    @Autowired
    private INVMLService invmlService;


    @PostMapping("/Kucunyuliang")
    @ApiOperation("库存余量查询")
    public Result<List<KucunyuliangVo>> kukunyuliang(@RequestBody KucunyuliangDto kucunyuliangDto){
        return Result.ok(kucunMapper.selectKucunyuliang(kucunyuliangDto));
    }


    @ApiOperation("库位转移")
    @PostMapping("/Movekuwei")
    public Result Movekuwei(@RequestBody ShaomiaoDTO shaomiaoDTO){
        return kucunService.updatekuwei(shaomiaoDTO);
    }

    @ApiOperation("库存余量excel导出")
    @PostMapping("/export")  // 改为 POST 请求，方便传递复杂参数
    public void exportExcel(@RequestBody KucunyuliangDto kucunyuliangDto, HttpServletResponse response) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            XSSFSheet sheet = workbook.createSheet("库存数据");

            // 创建表头
            String[] headers = {"品号", "品名", "规格", "批号", "数量", "单位", "库位编号", "库位名称", "仓库编号", "仓库名称", "备注"};
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 根据筛选条件获取数据
            List<KucunyuliangVo> dataList = kucunMapper.selectKucunyuliang(kucunyuliangDto);

            // 填充数据
            int rowNum = 1;
            for (KucunyuliangVo data : dataList) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(data.getML001());
                row.createCell(1).setCellValue(data.getMB002());
                row.createCell(2).setCellValue(data.getMB003());
                row.createCell(3).setCellValue(data.getML004());
                row.createCell(4).setCellValue(data.getML005());
                row.createCell(5).setCellValue(data.getMB004());
                row.createCell(6).setCellValue(data.getML003());
                row.createCell(7).setCellValue(data.getNI003());
                row.createCell(8).setCellValue(data.getML002());
                row.createCell(9).setCellValue(data.getMC002());
                row.createCell(10).setCellValue(data.getML011());
            }

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            byte[] bytes = baos.toByteArray();

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            String fileName = "库存余量.xlsx";
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 将字节数组写入响应输出流
            response.getOutputStream().write(bytes);
        }
        catch (UnsupportedEncodingException e){
            log.error("编码异常：", e);
            throw new RuntimeException("编码异常：" + e.getMessage(), e);
        }catch (IOException e){
            log.error("文件操作异常：", e);
            throw new RuntimeException("文件操作异常：" + e.getMessage(), e);
        }
        finally
        {
            workbook.close();
        }
    }

    @ApiOperation("INVML 模版 excel 导出")
    @PostMapping("/modelexport")  // 改为 POST 请求，方便传递复杂参数
    public void modelexport(HttpServletResponse response) throws IOException {
        XSSFWorkbook workbook = new XSSFWorkbook();
        try {
            XSSFSheet sheet = workbook.createSheet("库存数据");

            // 创建表头
            String[] headers = {"品号", "仓库", "库位", "批号", "库存数量", "库存包装数量", "上次盘点日", "最近入库日", "最近出库日", "备注", "数据计算标记"};
            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 将 workbook 写入字节数组输出流
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            workbook.write(baos);
            byte[] bytes = baos.toByteArray();

            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=库存余量导入模版下载.xlsx");
            // 设置响应长度
            response.setContentLength(bytes.length);
            // 将字节数组写入响应输出流
            response.getOutputStream().write(bytes);
        } catch (IOException e) {
            // 可以根据实际情况进行更详细的日志记录和异常处理
            System.out.println("文件操作异常：" + e.getMessage());
            throw new RuntimeException("文件操作异常：" + e.getMessage(), e);
        } finally {
            workbook.close();
        }
    }

    @ApiOperation("INVML文件导入excel导入")
    @PostMapping("/import")
    public Result importExcel(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.fail("文件为空");
            }
            LocalDateTime now = LocalDateTime.now();
            // 格式化日期时间部分
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
            String dateTimePart = now.format(formatter);
            // 获取毫秒部分
            int milli = now.getNano() / 1000000;
            // 拼接日期时间部分和毫秒部分
            String time = dateTimePart + String.format("%03d", milli);

            List<INVML> dataList = new ArrayList<>();
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);

            // 从第二行开始读取（跳过表头）
            for (int rowNum = 1; rowNum <= sheet.getLastRowNum(); rowNum++) {
                Row row = sheet.getRow(rowNum);
                if (row == null) {
                    continue;
                }

                INVML invml = new INVML();
                // 设置基础字段
                invml.setCompany("ZJQH");  // 设置你的公司代码
                invml.setCreator("ERP");
                invml.setUsrGroup("4000");  // 设置用户组
                invml.setCreateDate(time);
                invml.setModifier("ERP");
                invml.setModiDate(time);
                invml.setFlag(1);  // 设置标记

                // 设置业务字段
                invml.setMl001(getCellValueAsString(row.getCell(0)));  // 品号
                invml.setMl002(getCellValueAsString(row.getCell(1)));  // 仓库
                invml.setMl003(getCellValueAsString(row.getCell(2)));  // 库位
                invml.setMl004(getCellValueAsString(row.getCell(3)));  // 批号
                invml.setMl005(getCellValueAsDouble(row.getCell(4)));  // 库存数量
                invml.setMl006(getCellValueAsDouble(row.getCell(5)));  // 库存包装数量
                invml.setMl008(getCellValueAsString(row.getCell(6)));  // 上次盘点日
                invml.setMl009(getCellValueAsString(row.getCell(7)));  // 最近入库日
                invml.setMl010(getCellValueAsString(row.getCell(8)));  // 最近出库日
                invml.setMl011(getCellValueAsString(row.getCell(9))); // 备注
                invml.setMl012(getCellValueAsString(row.getCell(10))); // 数据计算标记
                dataList.add(invml);
            }
            boolean success=invmlService.saveOrUpdateBatchData(dataList);
            workbook.close();
            if (success){
                return Result.ok("导入成功，共导入 " + dataList.size() + " 条数据");
            }else {
                return Result.fail("导入失败！");
            }
        } catch (Exception e) {
            log.error("导入Excel失败", e);
            return Result.fail("导入失败：" + e.getMessage());
        }
    }

    // 获取单元格的字符串值
    private String getCellValueAsString(Cell cell) {
        if (cell == null) {
            return "";
        }
        cell.setCellType(CellType.STRING);
        return cell.getStringCellValue().trim();
    }

    // 获取单元格的数值
    private Double getCellValueAsDouble(Cell cell) {
        if (cell == null) {
            return 0.0;
        }
        try {
            cell.setCellType(CellType.NUMERIC);
            return cell.getNumericCellValue();
        } catch (Exception e) {
            return 0.0;
        }
    }

}
